package com.xywl.escort.view.pay.product

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BandCardListResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.bean.ProductPayApplyReq
import com.xywl.escort.bean.UserFundInfoResp
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_product_pay_dialog.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.math.BigDecimal
import javax.inject.Inject

/**
 * 商品支付弹窗界面
 */
@Route(path = "/xy/product/pay/dialog")
class ProductPayDialogActivity : BaseActivity(), ProductPayDialogContract.View {

    private val REQUEST_CODE_ADD_BAND_CARD = 27
    private var bandBean: BandCardListResp.DataBean.ListBean? = null
    // 需要支付的价钱
    @Autowired
    @JvmField
    internal var payMoney = BigDecimal("0") // 980 // 200 // 980

    @Autowired
    @JvmField
    var orderId = ""

    @Autowired
    @JvmField
    var type = 0

    // 用户账户余额
    private var accountFundsYuan = BigDecimal("0")

    // 使用账户支付金额
    private var accountPayMoney = BigDecimal("0") // 500 (500) // 500 (120) // 0 (0)

    // 使用银行卡支付
    private var thirdAccountPayPrice = BigDecimal("0") // 980 - 500 - 80 = 400 // 0 // 980 - 80 = 900

    private var isCheckedAccountMoney = false

    @Inject
    lateinit var mPresenter: ProductPayDialogContract.Presenter

    private var isAllCouponPay = false

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_product_pay_dialog)
        ARouter.getInstance().inject(this)

        initView()
        addListener()
        EventBus.getDefault().register(this)
    }

    private fun initView() {
        Timber.e("payMoney=$payMoney")
        Timber.e("orderId=$orderId")
        thirdAccountPayPrice = payMoney
        val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
        text_pay_price.text = strPayMoney
    }

    override fun onResume() {
        super.onResume()
        mPresenter.takeView(this)
        mPresenter.getBandCardList("DC", 1, 1)
        val userId = RxSPTool.getString(this, PreferenceKeys.USER_ID)
        mPresenter.getUserFunds(userId)
    }

    private fun addListener() {
        text_add_band_card.setOnClickListener {
            val userId = RxSPTool.getString(this, USER_ID)
            // 添加银行卡时校验是否设置支付密码
            mPresenter.isSetPayPwd(userId, 1)
        }

        image_close.setOnClickListener {
            if (type == 2) {
                ARouter.getInstance()
                        .build("/xy/order/purchase/detail")
                        .withString("orderId", orderId)
                        .navigation()
                EventBus.getDefault().post(MessageEvent(Constant.EventType.EVENT_PAY_SUCCESS, Constant.EventMessage.PAY_BALANCE_CANCEL))
            }
            finish()
        }

        sb_use_balance.setOnCheckedChangeListener { _, isChecked ->
            isCheckedAccountMoney = isChecked
            if (isChecked) {
                // 使用账户余额
                if (accountFundsYuan > payMoney) {
                    // 账户余额大于支付金额
                    accountPayMoney = payMoney
                    thirdAccountPayPrice = BigDecimal("0")
                } else {
                    // 账户余额小于支付金额
                    accountPayMoney = accountFundsYuan
                    thirdAccountPayPrice = payMoney.subtract(accountPayMoney)
                }
                val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
                text_pay_price.text = strPayMoney
            } else {
                // 不使用账户余额
                accountPayMoney = BigDecimal("0")
                thirdAccountPayPrice = payMoney
                val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
                text_pay_price.text = strPayMoney
            }
        }

        btn_confirm.setOnClickListener {
            if (accountPayMoney.toDouble() == 0.0 && thirdAccountPayPrice.toDouble() == 0.0) {
                isAllCouponPay = true
                val req = ProductPayApplyReq()
                req.orderId = orderId
                if (null != bandBean) {
                    req.bankCardNo = bandBean!!.bankCardNo
                }
                req.payment = thirdAccountPayPrice
                req.deduction = accountPayMoney
                req.payType = 0
                req.type = 4
                mPresenter.productPayApply(req)
            } else {
                isAllCouponPay = false
                if (accountPayMoney.toDouble() > 0) {
                    val userId = RxSPTool.getString(this, USER_ID)
                    // 使用余额支付时校验是否设置支付密码
                    mPresenter.isSetPayPwd(userId, 2)
                } else {
                    // 使用银行卡支付
                    val req = ProductPayApplyReq()
                    req.orderId = orderId
                    if (null != bandBean) {
                        req.bankCardNo = bandBean!!.bankCardNo
                    }
                    req.payment = thirdAccountPayPrice
                    req.deduction = accountPayMoney
                    req.payType = 0
                    req.type = 3
                    mPresenter.productPayApply(req)
                }
            }
        }

        text_add_band_card.setOnClickListener {
            val userId = RxSPTool.getString(this, USER_ID)
            mPresenter.isSetPayPwd(userId, 1)
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun getUserFundsSuccess(dataBean: UserFundInfoResp.DataBean?) {
        if (!TextUtils.isEmpty(dataBean!!.accountFundsYuan)) {
            accountFundsYuan = BigDecimal(dataBean.accountFundsYuan)
        } else {
            accountFundsYuan = BigDecimal("0")
        }
        val accountBalance = "账户余额(" + NumberFormatUtils.getInstance().format(accountFundsYuan.toDouble()) + "元)"
        text_account_balance.text = accountBalance
    }

    override fun getUserFundsFailure() {
        accountFundsYuan = BigDecimal("0")
    }

    override fun getBandCardListSuccess(dataBean: BandCardListResp.DataBean?) {
        val list = dataBean!!.list
        if (list.size > 0) {
            bandBean = list[0]
            val item = list[0]
            var bankName = item.bankName
            val bankCardNo = item.bankCardNo
            if (bankCardNo.length > 4) {
                bankName += " (" + bankCardNo.substring(bankCardNo.length - 4, bankCardNo.length) + ")"
            } else {
                bankName += " ($bankCardNo)"
            }
            text_add_band_card.visibility = View.GONE
            text_band_card.visibility = View.VISIBLE
            text_band_card.text = bankName
        } else {
            text_add_band_card.visibility = View.VISIBLE
            text_band_card.visibility = View.GONE
        }
    }

    override fun getBandCardListFailure() {
        Timber.e("getBandCardListFailure")
        text_add_band_card.visibility = View.VISIBLE
        text_band_card.visibility = View.GONE
    }

    override fun hasSetPayPwd(type: Int) {
        when (type) {
            1 -> {
                ARouter.getInstance().build("/xy/verify/pay/pwd")
                        .withString("path", "/xy/band/card/bind")
                        .navigation()
            }
            2 -> {
                if (thirdAccountPayPrice.toDouble() > 0) {
                    // 使用余额+银行卡支付
                    var bankCardNo = ""
                    if (null != bandBean) {
                       bankCardNo = bandBean!!.bankCardNo
                    }
                    ARouter.getInstance().build("/xy/verify/pay/pwd")
                            .withInt("type", 3)
                            .withString("path", "/xy/product/pay/confirm")
                            .withString("orderId", orderId)
                            .withString("bankCardNo", bankCardNo)
                            .withObject("payment", thirdAccountPayPrice)
                            .withObject("deduction", accountPayMoney)
                            .withInt("payType", 0)
                            .withInt("payStatus", 2)
                            .navigation()
                } else {
                    // 使用余额支付
                    var bankCardNo = ""
                    if (null != bandBean) {
                        bankCardNo = bandBean!!.bankCardNo
                    }
                    ARouter.getInstance().build("/xy/verify/pay/pwd")
                            .withInt("type", 3)
                            .withString("orderId", orderId)
                            .withString("bankCardNo", bankCardNo)
                            .withObject("payment", thirdAccountPayPrice)
                            .withObject("deduction", accountPayMoney)
                            .withInt("payType", 0)
                            .withInt("payStatus", 1)
                            .navigation()
                }
            }
            else -> {
            }
        }
    }

    override fun noSetPayPwd() {
        ARouter.getInstance().build("/xy/pwd/setting/pay").navigation()
    }

    override fun findIsFitPayPwdFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun productPayApplySuccess(data: String?) {
        if (isAllCouponPay) {
            ARouter.getInstance()
                    .build("/xy/order/purchase/detail")
                    .withString("orderId", orderId)
                    .navigation()
            EventBus.getDefault().post(MessageEvent(Constant.EventType.EVENT_PAY_SUCCESS, Constant.EventMessage.PAY_BALANCE_CANCEL))
            finish()
        } else {
            var bankCardNo = ""
            if (null != bandBean) {
                bankCardNo = bandBean!!.bankCardNo
            }
            ARouter.getInstance().build("/xy/product/pay/confirm")
                    .withString("orderId", orderId)
                    .withString("bankCardNo", bankCardNo)
                    .withObject("payment", thirdAccountPayPrice)
                    .withObject("deduction", accountPayMoney)
                    .withInt("payType", 0)
                    .withInt("payStatus", 3)
                    .navigation()
        }
    }

    override fun productPayApplyFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("ProjectPayDialogActivity").e("event.message=" + event.message)
        Timber.tag("ProjectPayDialogActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_PAY_SUCCESS -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.PAY_SUCCESS) {
                        finish()
                    } else if (message == Constant.EventMessage.PAY_BALANCE_SUCCESS) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_ADD_BAND_CARD -> {
                    data?.let {
                        bandBean = data.getSerializableExtra("bandBean") as BandCardListResp.DataBean.ListBean
                        Timber.tag("ProjectPayDialogActivity").e("bandBean.bankName=${bandBean!!.bankName}")
                        var bankName = bandBean!!.bankName
                        val bankCardNo = bandBean!!.bankCardNo
                        if (bankCardNo.length > 4) {
                            bankName += " (" + bankCardNo.substring(bankCardNo.length - 4, bankCardNo.length) + ")"
                        } else {
                            bankName += " ($bankCardNo)"
                        }
                        text_band_card.text = bankName
                    }
                }
                else -> {
                }
            }
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (type == 2) {
            ARouter.getInstance()
                    .build("/xy/order/purchase/detail")
                    .withString("orderId", orderId)
                    .navigation()
            EventBus.getDefault().post(MessageEvent(Constant.EventType.EVENT_PAY_SUCCESS, Constant.EventMessage.PAY_BALANCE_CANCEL))
        }
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
